package com.example.user.customviewdemo.emoji;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;

import com.example.user.customviewdemo.R;
import com.example.user.customviewdemo.tabviewpager.TabViewPagerActivity;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

public class RichEditTextActivity extends AppCompatActivity {

    @Bind(R.id.edit_text)
    EditText editText;
    @Bind(R.id.button)
    Button button;
    @Bind(R.id.gridview)
    GridView gridview;
    @Bind(R.id.edit_text2)
    EditText editText2;


    private InputMethodManager imm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rich_edit_text);
        ButterKnife.bind(this);

        //获取输入管理对象
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();


        //处理button事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // gridview.setVisibility(View.VISIBLE);
                Intent intent = new Intent(RichEditTextActivity.this, TabViewPagerActivity.class);
                startActivity(intent);
            }
        });

        //处理gradview事件
        GridViewAdapter adapter = new GridViewAdapter(this);
        gridview.setAdapter(adapter);
        adapter.setData(getData());
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int resId = (Integer) (((GridViewAdapter) parent.getAdapter()).getItem(position));
                addExpressToEdit(resId);
            }
        });


    }

    /**
     * 控制显示和隐藏输入法
     *
     * @param imm
     * @param isVisible
     */
    public void showKeybord(InputMethodManager imm, boolean isVisible) {
        if (isVisible) {
            imm.showSoftInput(button, InputMethodManager.SHOW_FORCED);
        } else {
            imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 利用反射机制获取输入软键盘的高度,但仅当只有软键盘显示出来了才可以获取到
     *
     * @param imm
     * @return
     */
    public int getKeyBordVisibleHeight(InputMethodManager imm) {
        if (imm == null) {
            throw new NullPointerException("your instance of InputMethodManager is null!!");
        }
        int height = 0;
        try {
            Class clazz = imm.getClass();
            Method method = clazz.getDeclaredMethod("getInputMethodWindowVisibleHeight");
            String methodName = method.getName();
            method.setAccessible(true);
            height = (Integer) method.invoke(imm);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return height;
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    /**
     * 添加表情到edittext
     *
     * @param resId
     */
    private void addExpressToEdit(int resId) {
        Drawable drawable = getResources().getDrawable(resId);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        SpannableString spannableString = new SpannableString("img");
        ImageSpan span = new ImageSpan(drawable);
        spannableString.setSpan(span, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        int cusor = editText.getSelectionStart();
        editText.getText().insert(cusor, spannableString);
    }

    /**
     * 利用反射获取mipmap下所有以emoji开始命名的图片资源id
     *
     * @return 获取数据源
     */
    private ArrayList<Integer> getData() {
        ArrayList<Integer> data = new ArrayList<>();
        Field[] fields = R.mipmap.class.getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            if (name.startsWith("emoji")) {
                try {
                    int resId = field.getInt(name);
                    data.add(resId);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }

    static class GridViewAdapter extends BaseAdapter {

        private ArrayList<Integer> data = new ArrayList<>();
        private LayoutInflater inflater;

        public GridViewAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void setData(ArrayList<Integer> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_emoji_gradview_layout, null);
            }
            ImageView imageView = (ImageView) convertView;
            imageView.setImageResource(data.get(position));
            return convertView;
        }
    }
}
